package nbcp.db.mongo.repository

import nbcp.base.extend.AsString
import nbcp.base.extend.*

import nbcp.db.mongo.entity.WxFormId
import nbcp.db.mongo.entity.SysLog
import nbcp.db.mongo.mor
import nbcp.db.mongo.*
import nbcp.db.mongo.*
import nbcp.db.mongo.table.*
import java.time.LocalDateTime


fun  ShopGroup.WxFormIdEntity .findValidateMessageId(openId: String): String {
    var formId = mor.shop.wxFormId.query()
            .where(mor.shop.wxFormId.openId match openId)
            .where(mor.shop.wxFormId.used match false)
            .where(mor.shop.wxFormId.createAt match_greaterThan LocalDateTime.now().minusDays(6))
            .orderBy{it.id.asc}
            .toEntity();

    if (formId == null) {
        var log = SysLog();
        log.module = "wx"
        log.type = "error"
        log.msg = "找不到 openId 的 formId"

        mor.system.sysLog.insert(log)

        return "";
    }

    mor.shop.wxFormId.updateById(formId.id)
            .set(mor.shop.wxFormId.used, true)
            .set(mor.shop.wxFormId.usedAt, LocalDateTime.now())
            .exec()


    return formId.formId.AsString(formId.prePayId);
}

